﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace W.Carrier.Repostiory
{
    public class BaseRepositoy<T> : IRepository<T> where T : class, new()
    {
        /// <summary>
        /// 上下文
        /// </summary>
        private readonly EFCoreDbContext _context;
        public BaseRepositoy(EFCoreDbContext context)
        {
            _context = context;
        }
        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public async Task<int> AddAsync(T t)
        {
            await _context.AddAsync(t);
            return await _context.SaveChangesAsync();
        }
        /// <summary>
        /// 列表显示
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<T>> GetAllAsync()
        {
           return  await _context.Set<T>().ToListAsync();
        }

        public async Task<List<T>> GetAsync(Expression<Func<T,bool>> expr)
        {
            return await _context.Set<T>().Where(expr).ToListAsync();
        }

        public async Task<T> GetModelAsync(int id)
        {
            return await _context.Set<T>().FindAsync(id);
        }

        public async Task<int> Update(T t)
        {
             _context.Update(t);
            return await _context.SaveChangesAsync();
        }

        public async Task<int> UpdateRange(List<T> entities)
        {
            _context.UpdateRange(entities);
            return await _context.SaveChangesAsync();
        }
    }
}
